package wangjg.game.layer;


public class Sprite extends Layer {
	Image image = null;

	int numberFrames; // = 0;

	int[] frameCoordsX;

	int[] frameCoordsY;

	int srcFrameWidth;

	int srcFrameHeight;

	int[] frameSequence;

	private int sequenceIndex; // = 0

	public Sprite(Image image, int frameWidth, int frameHeight) {
		super(frameWidth, frameHeight);
	}
	
	public void setFrameSequence(int sequence[]) {

		if (sequence == null) {
			// revert to the default sequence
			sequenceIndex = 0;
			frameSequence = new int[numberFrames];
			// copy frames indices into frameSequence
			for (int i = 0; i < numberFrames; i++) {
				frameSequence[i] = i;
			}
			return;
		}

		if (sequence.length < 1) {
			throw new IllegalArgumentException();
		}

		for (int i = 0; i < sequence.length; i++) {
			if (sequence[i] < 0 || sequence[i] >= numberFrames) {
				throw new ArrayIndexOutOfBoundsException();
			}
		}
		frameSequence = new int[sequence.length];
		System.arraycopy(sequence, 0, frameSequence, 0, sequence.length);
		sequenceIndex = 0;
	}

	public void setFrame(int sequenceIndex) {
		if (sequenceIndex < 0 || sequenceIndex >= frameSequence.length) {
			throw new IndexOutOfBoundsException();
		}
		this.sequenceIndex = sequenceIndex;
	}

	public final int getFrame() {
		return sequenceIndex;
	}

	public int getRawFrameCount() {
		return numberFrames;
	}

	public int getFrameSequenceLength() {
		return frameSequence.length;
	}

	public void nextFrame() {
		sequenceIndex = (sequenceIndex + 1) % frameSequence.length;
	}

	public void prevFrame() {
		if (sequenceIndex == 0) {
			sequenceIndex = frameSequence.length - 1;
		} else {
			sequenceIndex--;
		}
	}

	public final void paint(Graphics g) {
		if (g == null) {
			throw new NullPointerException();
		}

		if (visible) {
			g.drawRegion(this.image, 
				     frameCoordsX[frameSequence[sequenceIndex]],
				     frameCoordsY[frameSequence[sequenceIndex]],
				     srcFrameWidth, 
				     srcFrameHeight,
				     0,
				     this.x, 
				     this.y, 
				     Graphics.TOP | Graphics.LEFT);
		}

	}

}
